package com.mujin.keji.collectionsystem.module.tripplan.views;

import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.route.MassTransitRouteLine;
import com.mujin.keji.collectionsystem.CcsApplication;
import com.mujin.keji.collectionsystem.R;
import com.mujin.keji.collectionsystem.base.BaseActivity;
import com.mujin.keji.collectionsystem.base.BaseDto;
import com.mujin.keji.collectionsystem.dialog.BaseNiceDialog;
import com.mujin.keji.collectionsystem.dialog.NiceDialog;
import com.mujin.keji.collectionsystem.dialog.ViewConvertListener;
import com.mujin.keji.collectionsystem.dialog.ViewHolder;
import com.mujin.keji.collectionsystem.listeners.CustomItemClickListener;
import com.mujin.keji.collectionsystem.module.outboundtask.dto.ApplyCaseDto;
import com.mujin.keji.collectionsystem.module.outboundtask.dto.BoundTaskDto;
import com.mujin.keji.collectionsystem.module.outboundtask.dto.VisitCaseDto;
import com.mujin.keji.collectionsystem.module.outboundtask.viewmodel.BoundTaskListViewModel;
import com.mujin.keji.collectionsystem.module.outboundtask.views.CaseInformationActivity;
import com.mujin.keji.collectionsystem.module.outboundtask.vo.ApplyCaseVo;
import com.mujin.keji.collectionsystem.module.tripplan.adapter.BusPlanDetailAdapter;
import com.mujin.keji.collectionsystem.module.tripplan.dto.MassTransitRouteLineDto;
import com.mujin.keji.collectionsystem.module.tripplan.dto.QueryPlanDetailDto;
import com.mujin.keji.collectionsystem.overlayutil.MassTransitRouteOverlay;
import com.mujin.keji.collectionsystem.utils.DateUtil;
import com.mujin.keji.collectionsystem.utils.EmptyUtils;
import com.mujin.keji.collectionsystem.utils.ToastUtils;
import com.mujin.keji.collectionsystem.widget.CustomLinearLayoutManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 行程规划详情
 *
 * @author weishixiong
 * @Time 2018-05-17
 */
public class BusPlanDetailActivity extends BaseActivity implements CustomItemClickListener, View.OnClickListener {
    private MapView bmapView;
    private TextView tvMark;
    private TextView tvWalkDistance;
    private TextView tvTime;
    private LinearLayout llTop;
    private TextView tvBusLine;
    private TextView tvStartBus;
    //地图对象
    private BaiduMap baiduMap;
    private double currentLat;
    private double currentLon;
    private String currentAdress;
    private List<LatLng> mPointList = new ArrayList<>();
    private RecyclerView recyclerview;
    private TextView tvTargetAdress;
    private BusPlanDetailAdapter busPlanDetailAdapter;
    private CustomLinearLayoutManager linearLayoutManager;
    private List<List<MassTransitRouteLine.TransitStep>> transitStepList;
    private ImageView ivAnHint;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        CcsApplication.addActivity(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CcsApplication.removeActivity(this);
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        bmapView.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void getBusPlanDetail(MassTransitRouteLineDto massTransitRouteLineDto) {
        try {
            queryPlanDetailDto = massTransitRouteLineDto.getQueryPlanDetailDto();
            mPointList.add(new LatLng(massTransitRouteLineDto.getLatLonVo().getCurrentLat(), massTransitRouteLineDto.getLatLonVo().getCurrentLon()));
            mPointList.add(new LatLng(massTransitRouteLineDto.getLatLonVo().getTargetLat(), massTransitRouteLineDto.getLatLonVo().getTargetLon()));
            initMapLocation(massTransitRouteLineDto.getLatLonVo().getCurrentLat(), massTransitRouteLineDto.getLatLonVo().getCurrentLon());
            showPointsInBaiduMap(mPointList);
            tvTime.setText(DateUtil.minForDay(massTransitRouteLineDto.getMassTransitRouteLine().getDuration() / 60));
            int distance = 0;
            //获取步行的距离
            //遍历每条路线的步骤
            this.transitStepList = massTransitRouteLineDto.getMassTransitRouteLine().getNewSteps();
            for (int j = 0; j < massTransitRouteLineDto.getMassTransitRouteLine().getNewSteps().size(); j++) {
                //步骤
                List<MassTransitRouteLine.TransitStep> transitStepList = massTransitRouteLineDto.getMassTransitRouteLine().getNewSteps().get(j);
                //
                for (int k = 0; k < transitStepList.size(); k++) {
                    String instructions = transitStepList.get(k).getInstructions();
                    //
                    if (instructions.contains("步行") && instructions.contains("米")) {
                        //提取文字中的数字
                        String regEx = "[^0-9]";
                        Pattern p = Pattern.compile(regEx);
                        Matcher m = p.matcher(instructions);
                        distance += +Integer.parseInt(m.replaceAll("").trim());
                        tvWalkDistance.setText("步行" + distance + "米");
                    }
                    if (EmptyUtils.isNotEmpty(transitStepList.get(k).getBusInfo())) {
                        //Logger.d(TAG, "交通工具---" + j + ":" + j + ":" + k + ":" + transitStepList.get(k).getBusInfo().getName());
                        tvBusLine.setText(tvBusLine.getText().toString() + "/" + transitStepList.get(k).getBusInfo().getName());
                        if (TextUtils.isEmpty(tvStartBus.getText().toString())) {
                            tvStartBus.setText(transitStepList.get(k).getBusInfo().getDepartureStation() + "上车");
                        }
                    }

                }
            }
            if (massTransitRouteLineDto.isMinTime()) {
                tvMark.setText("时间短");
                tvMark.setVisibility(View.VISIBLE);
            } else if (massTransitRouteLineDto.isMinWakl()) {
                tvMark.setText("少步行");
                tvMark.setVisibility(View.VISIBLE);
            } else {
                tvMark.setVisibility(View.GONE);
            }

            linearLayoutManager = new CustomLinearLayoutManager(this);
            // linearLayoutManager.setScrollEnabled(false);
            recyclerview.setLayoutManager(linearLayoutManager);
            busPlanDetailAdapter = new BusPlanDetailAdapter("起点（我的位置）", "终点(" + massTransitRouteLineDto.getLatLonVo().getTargetAdress() + ")", this, this.transitStepList, this);
            recyclerview.setAdapter(busPlanDetailAdapter);
            /**
             * 绘制公交路线图
             *
             * @param transitRouteLine
             */
            MassTransitRouteOverlay overlay = new MassTransitRouteOverlay(baiduMap);
            //设置公交路线规划数据
            overlay.setData(massTransitRouteLineDto.getTransitRouteLine());
            //将公交路线规划覆盖物添加到地图中
            overlay.addToMap();
            overlay.zoomToSpan();
            //
            MapStatus.Builder builder = new MapStatus.Builder();
            //builder.zoom(10.0f);//这里设置了缩放的比例，float类型。
            baiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
        } catch (Exception e) {
            //Logger.d(TAG, "getBusPlanDetail: " + e);
        }

    }

    private BoundTaskListViewModel boundTaskListViewModel;

    @Override
    protected void createViewModel() {
        boundTaskListViewModel = ViewModelProviders.of(this).get(BoundTaskListViewModel.class);
    }

    private Button btnOk;


    @Override
    public int intiLayout() {
        return R.layout.activity_busplandetail;
    }

    @Override
    public void initView() {
        bmapView = (MapView) findViewById(R.id.bmapView);
        tvMark = (TextView) findViewById(R.id.tv_mark);
        tvWalkDistance = (TextView) findViewById(R.id.tv_walk_distance);
        tvTime = (TextView) findViewById(R.id.tv_time);
        llTop = (LinearLayout) findViewById(R.id.ll_top);
        tvBusLine = (TextView) findViewById(R.id.tv_bus_line);
        tvStartBus = (TextView) findViewById(R.id.tv_start_bus);
        recyclerview = (RecyclerView) findViewById(R.id.recyclerview);
        ivAnHint = (ImageView) findViewById(R.id.iv_an_hint);
        btnOk = (Button) findViewById(R.id.btn_ok);
        recyclerview.setFocusable(false);
        //tvTargetAdress = (TextView) findViewById(R.id.tv_target_adress);
        setCenterTitle("行程规划", "#FFFFFF");
        setleftImage(R.drawable.image_arrow_left_white, true, null);
        baiduMap = bmapView.getMap();
        //{"10m", "20m", "50m", "100m", "200m", "500m", "1km",
        // "2km", "5km", "10km", "20km", "25km", "50km", "100km", "200km", "500km", "1000km", "2000km"}
        //Level依次为：20、19、18、17、16、15、14、13、12、11、10、9、8、7、6、5、4、3


    }

    private QueryPlanDetailDto queryPlanDetailDto;

    @Override
    public void initData() {
    }

    /**
     * 定位到某个坐标点
     *
     * @param latitude
     * @param longitude
     */
    private void initMapLocation(double latitude, double longitude) {
        // 开启定位图层
        baiduMap.setMyLocationEnabled(true);
        // 构造定位数据
        MyLocationData locData = new MyLocationData.Builder()
                .accuracy(200)
                // 此处设置开发者获取到的方向信息，顺时针0-360
                .direction(100).latitude(latitude)
                .longitude(longitude).build();
        // 设置定位数据
        baiduMap.setMyLocationData(locData);
        // 设置定位图层的配置（定位模式，是否允许方向信息，用户自定义定位图标）
        BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory
                .fromResource(R.drawable.image_now_adress);
        MyLocationConfiguration config = new MyLocationConfiguration(MyLocationConfiguration.LocationMode.FOLLOWING, true, mCurrentMarker);
        baiduMap.setMyLocationConfiguration(config);
        // 当不需要定位图层时关闭定位图层
        baiduMap.setMyLocationEnabled(false);


    }

    @Override
    public void initListener() {
        ivAnHint.setOnClickListener(this);
        btnOk.setOnClickListener(this);
    }


    /**
     * 在地图上展示各个点
     *
     * @param pointList
     */
    private void showPointsInBaiduMap(List<LatLng> pointList) {
//        //创建OverlayOptions的集合
//        List<OverlayOptions> options = new ArrayList<>();
//        //构建Marker图标
//        BitmapDescriptor bitmap = BitmapDescriptorFactory
//                .fromResource(R.drawable.image_location);
//        for (int i = 0; i < pointList.size(); i++) {
//            //构建MarkerOption，用于在地图上添加Marker
//            OverlayOptions option = new MarkerOptions()
//                    .position(pointList.get(i))
//                    .icon(bitmap);
//            //在地图上添加Marker，并显示
//            options.add(option);
//        }
//        //在地图上批量添加
//        baiduMap.addOverlays(options);


    }


    @Override
    public void onItemClick(View view, int position) {

    }

    List<BoundTaskDto> boundTaskDtoList;
    private boolean isHasCase;//是否有案件
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_an_hint:
                if (recyclerview.getVisibility() == View.VISIBLE) {
                    recyclerview.setVisibility(View.GONE);
                } else {
                    recyclerview.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.btn_ok:
                NiceDialog.init()
                        .setLayoutId(R.layout.dialog_to_tip)
                        .setConvertListener(new ViewConvertListener() {
                            @Override
                            public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
                                TextView tvLeft = (TextView) holder.getView(R.id.tv_left);
                                TextView tvRight = (TextView) holder.getView(R.id.tv_right);
                                tvLeft.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        dialog.dismiss();
                                    }
                                });
                                tvRight.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        dialog.dismiss();
                                        //获取当前外访的任务
                                        ApplyCaseVo vo = new ApplyCaseVo();
                                        vo.setStatus(1);//待外访案件
                                        vo.setTimeSort(2);//时间倒叙排序
//                                        vo.setPageSize(20);//每页20
//                                        vo.setCurrentPage(1);//当前页1
                                        getLoadingDialog().showDialog();
                                        boundTaskListViewModel.getLiveData(vo).observe(BusPlanDetailActivity.this, new Observer<BaseDto<ApplyCaseDto>>() {
                                            @Override
                                            public void onChanged(@Nullable BaseDto<ApplyCaseDto> applyCaseDtoBaseDto) {
                                                if (EmptyUtils.isNotEmpty(applyCaseDtoBaseDto.getData()) && EmptyUtils.isNotEmpty(applyCaseDtoBaseDto.getData().getItems())) {
                                                    boundTaskDtoList = applyCaseDtoBaseDto.getData().getItems();
                                                    if (!EmptyUtils.isNotEmpty(queryPlanDetailDto)) {
                                                        getLoadingDialog().dismiss();
                                                        ToastUtils.showToast("当前案件已经被回收，无法查看");
                                                        return;
                                                    }
                                                    try {
                                                        for (int i = 0; i < boundTaskDtoList.size(); i++) {
                                                            if (queryPlanDetailDto.getCaseId().equals(boundTaskDtoList.get(i).getCaseId())) {
                                                                isHasCase = true;
                                                                getLoadingDialog().dismiss();
                                                                VisitCaseDto visitCaseDto = new VisitCaseDto();
                                                                boundTaskDtoList.get(i).setStatus(1);
                                                                visitCaseDto.setVisitApplyId(String.valueOf(boundTaskDtoList.get(i).getId()));
                                                                visitCaseDto.setName(boundTaskDtoList.get(i).getVisitName());
                                                                visitCaseDto.setTaskTime(boundTaskDtoList.get(i).getAllotTime());
                                                                visitCaseDto.setVisitAddress(boundTaskDtoList.get(i).getVisitAddress());
                                                                visitCaseDto.setDto(boundTaskDtoList.get(i));
                                                                //案件信息
                                                                Intent intent = new Intent(BusPlanDetailActivity.this, CaseInformationActivity.class);
                                                                intent.putExtra("visitCaseDto", visitCaseDto);
                                                                intent.putExtra("isTrip",true);
                                                                startActivity(intent);
                                                                break;

                                                            }
                                                        }
                                                        if(!isHasCase){
                                                            getLoadingDialog().dismiss();
                                                            ToastUtils.showToast("当前案件已经被回收，无法查看");
                                                        }


                                                    } catch (Exception e) {
                                                        getLoadingDialog().dismiss();
                                                        ToastUtils.showToast("客户端异常，请稍后再试");
                                                    }

                                                } else {
                                                    getLoadingDialog().dismiss();
                                                    ToastUtils.showToast("当前案件已经被回收，无法查看");
                                                }
                                            }
                                        });


                                    }
                                });

                            }
                        })
                        .show(getSupportFragmentManager());
                break;
        }
    }
}
